//
// Created by Apple on 2020/10/7.
//

#ifndef P2PCLIENT_TCP_CLIENT_H
#define P2PCLIENT_TCP_CLIENT_H

#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include "asio.hpp"
#include "chat_message.h"
#include "udp_client.h"
#include <vector>
#include <string>

using asio::ip::tcp;

typedef std::deque<chat_message> chat_message_queue;

class tcp_client
{
public:
    tcp_client(asio::io_context& io_context, const tcp::resolver::results_type& endpoints, UdpClient& udp_client)
            : io_context_(io_context)
            , socket_(io_context)
            , udp_client_(udp_client)

    {
        do_connect(endpoints);
    }

    void write(const chat_message& msg);
    void close();
    std::vector<std::string> get_peer(){
        return peer_;
    }

    asio::io_context& context() {
        return io_context_;
    }

private:
    void do_connect(const tcp::resolver::results_type& endpoints);
    void do_read_header();
    void do_read_body();
    void do_write();

private:
    asio::io_context& io_context_;
    tcp::socket socket_;
    chat_message read_msg_;
    chat_message_queue write_msgs_;
    UdpClient& udp_client_;
    std::vector<std::string> peer_;
};

#endif //P2PCLIENT_TCP_CLIENT_H
